package org.ccay.web.support.filter;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.text.MessageFormat;

import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.ccay.core.exception.ExceptionHandler;
import org.ccay.core.exception.FaultVO;
import org.ccay.core.ioc.Ccay;
import org.ccay.core.request.IRequestContext;
import org.ccay.core.request.impl.RequestContext;
import org.ccay.core.request.impl.RequestContextConstants;
import org.ccay.core.util.EncodingUtil;
import org.ccay.core.util.JsonUtil;
import org.ccay.core.util.MimeTypeUtil;
import org.ccay.web.support.WebRequestVO;
import org.ccay.web.support.internal.impl.HttpCacheConfigBean;
import org.ccay.web.support.internal.impl.RequestUtil;
import org.springframework.web.util.HtmlUtils;

/**
 * 响应处理辅助工具	
 */
public final class ResponseUtil {
	/**
	 * 最后更新时间的Header名
	 */
	static final String LAST_MODIFIED_NAME = "Last-Modified";
	private ResponseUtil(){
	}
	/**
	 * 设置response的 ContentType	 由于某些浏览器对于css文件不能自动识别，需要设置下文件里类型
	 * @param response
	 * @param fileType
	 */
	public static void setContentType(ServletResponse response,String fileType){ 
		response.setContentType(MimeTypeUtil.getTypeBySuffix(fileType));
	} 
	
	/** 
	 * 发送响应
	 * @param response
	 * @param httpCode
	 * @param fault
	 * @throws IOException
	 */
	public static void sendError2Response(HttpServletResponse response, int httpCode, FaultVO fault){
		try {
			response.setStatus(httpCode);
			response.getWriter().write(JsonUtil.getJsonString(fault));
		} catch (IOException e) {
			ExceptionHandler.logException(e);
		}
	}
	/** 
	 * 发送错误
	 * @param request
	 * @param response
	 * @param fault
	 */
	public static void sendErrorPage(HttpServletRequest request, HttpServletResponse response, FaultVO fault) {
		String shortUri = RequestUtil.getShortUri(request);
		try{
			if( shortUri.startsWith("/pub/")){
				//防止循环跳转
				response.getWriter().write(fault.getMessage());
				return ;
			}			 
			response.sendRedirect(RequestUtil.getContextPath(request) + getErrorUrl(fault));			
		}catch(IOException e){
			ExceptionHandler.logException(e);
		}
	}
	
	//错误消息URL中文
	private static final String errorPatternZh = "pub/error.zh_CN.html?code={0}&msg={1}";
	//错误消息的URL
	private static final String  errorPattern = "pub/error.html?code={0}&msg={1}";
	/** 
	 * 获取 Error Url
	 * @param msg
	 * @return
	 * @throws UnsupportedEncodingException
	 */
	private static String getErrorUrl(FaultVO faultVO) throws UnsupportedEncodingException{
		IRequestContext requestContext = RequestContext.getCurrent(true);
		
		if(requestContext != null && "zh_CN".equals(requestContext.getUserLanguage())){
			return  MessageFormat.format(errorPatternZh, faultVO.getHttpCode() , URLEncoder.encode(faultVO.getMessage(), EncodingUtil.UTF_8));
		}
		 
		return  MessageFormat.format(errorPattern, faultVO.getHttpCode() , URLEncoder.encode(faultVO.getMessage(), EncodingUtil.UTF_8));
	}
 
	/** 
	 * 为服务方法设置缓存
	 * @param httpRequest
	 * @param httpResponse
	 */
	public static void setCache4Service(HttpServletRequest httpRequest, HttpServletResponse httpResponse) {	 
		
		setNoCache(httpResponse); 
	}
	
	
	static String noCacheHeaderValue="no-cache,no-store,max-age=0";
	static boolean sendNoCacheWithExpires = true;
	/** 
	 * 设置禁止缓存
	 * @param httpResponse
	 */
	public static void setNoCache(HttpServletResponse httpResponse) {
		httpResponse.setHeader(  "Cache-Control", noCacheHeaderValue);
		//兼容老浏览器
		if(sendNoCacheWithExpires){
			httpResponse.setDateHeader("Expires", 0);
			httpResponse.setHeader("Pragma", "no-cache");
		}
	}
	
	private static HttpCacheConfigBean httpCacheConfig = Ccay.getContext().getBean("httpCacheConfigBean",HttpCacheConfigBean.class);
	/** 
	 * 设置缓存	
	 * @param response
	 * @param fileType
	 */
	public static void setCache4Resource(HttpServletResponse response, WebRequestVO webRequest) {
		String fileType = webRequest.getFileType();		
		
		if("html".equals(fileType)){
			response.setHeader("Cache-Control", "max-age=" +httpCacheConfig.getHtmlResourceAge() );
		}else if("js".equals(fileType) || "css".equals(fileType)){
			response.setHeader("Cache-Control", "max-age=" + httpCacheConfig.getDynamicResourceAge());
		//add hufeng 00214522 2013.10.21 给service添加缓存;
		}else if(RequestContextConstants.TYPE_PRIVATE_SERVICES.equals(fileType)){
			response.setHeader("Cache-Control", "max-age=" + httpCacheConfig.getServiceResourceAge());
		}
		//add end;
		else{
			response.setHeader("Cache-Control", "max-age=" + httpCacheConfig.getStaticResourceAge());
		}		
	}
	
	/** 
	 * 写入消息到 Response
	 * 
	 * @since 2012-6-27
	 * @param response
	 * @param msg
	 */
	public static void writeResponse(HttpServletResponse response, String msg) {
		writeResponse(response, msg, true);
	}
	
	/** 
	 * 写入消息到 Response	
	 * @param response
	 * @param msg
	 * @param encode 是否转码
	 */
	public static void writeResponse(HttpServletResponse response, String msg, boolean encode) {
		try {
			response.getWriter().write(encode ? HtmlUtils.htmlEscape(msg) : msg);
		} catch (IOException e) {
			ExceptionHandler.logException(e);
		}
	}
	/**
	 * 处理资源的304响应码
	 * @param response
	 * @param webRequest
	 * @param serverModifiedTime
	 * @return
	 */
	public static boolean process304(HttpServletResponse response, WebRequestVO webRequest, long serverModifiedTime) {
		if( RequestUtil.isNotModified(webRequest.getLastModified(), serverModifiedTime) ){
			response.setStatus(HttpServletResponse.SC_NOT_MODIFIED);
			return true;
		}		
		
		if(serverModifiedTime > 0){
			response.setDateHeader(ResponseUtil.LAST_MODIFIED_NAME, serverModifiedTime);
		}
		
		return false;
	}
	
	//设置缓存有效时间
	public static void setCache(HttpServletResponse response,Integer cacheTime) {
		response.setHeader("Cache-Control", "max-age=" + cacheTime);
		response.setHeader("Pragma", "cache");
		response.setDateHeader("Expires", System.currentTimeMillis() + cacheTime * 1000L);
	}
}
